import type { User, UserStats, UserManagementAction } from "@/types";
import { API_BASE_URL } from "@/config/api";

/**
 * 基于数据库的用户管理API
 */
export class UserManagementDBAPI {
  private static baseURL = API_BASE_URL;

  /**
   * 获取所有用户
   */
  static async getAllUsers(
    page = 1,
    limit = 10,
    search = "",
  ): Promise<{ users: User[]; total: number; page: number; totalPages: number }> {
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        limit: limit.toString(),
        search,
      });

      const response = await fetch(`${this.baseURL}/users?${params}`);
      if (!response.ok) {
        throw new Error("获取用户列表失败");
      }

      const result = await response.json();

      // 适配新的API响应格式
      if (result.success && result.data) {
        return {
          users: result.data.users,
          total: result.data.pagination.total,
          page: result.data.pagination.page,
          totalPages: result.data.pagination.pages,
        };
      } else {
        throw new Error(result.message || "获取用户列表失败");
      }
    } catch (error) {
      console.error("获取用户列表失败:", error);
      throw error;
    }
  }

  /**
   * 根据ID获取用户
   */
  static async getUserById(id: string): Promise<User | null> {
    try {
      const response = await fetch(`${this.baseURL}/users/${id}`);
      if (!response.ok) {
        if (response.status === 404) {
          return null;
        }
        throw new Error("获取用户信息失败");
      }

      return await response.json();
    } catch (error) {
      console.error("获取用户信息失败:", error);
      throw error;
    }
  }

  /**
   * 更新用户信息
   */
  static async updateUser(userId: string, updates: Partial<User>): Promise<boolean> {
    try {
      const response = await fetch(`${this.baseURL}/users/${userId}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(updates),
      });

      if (!response.ok) {
        throw new Error("更新用户信息失败");
      }

      return true;
    } catch (error) {
      console.error("更新用户信息失败:", error);
      return false;
    }
  }

  /**
   * 获取用户统计数据
   */
  static async getUserStats(): Promise<UserStats> {
    try {
      const response = await fetch(`${this.baseURL}/users/stats`);
      if (!response.ok) {
        throw new Error("获取用户统计失败");
      }

      const result = await response.json();

      // 适配后端返回的数据格式
      if (result.success && result.data) {
        return result.data;
      } else {
        throw new Error(result.message || "获取用户统计失败");
      }
    } catch (error) {
      console.error("获取用户统计失败:", error);
      // 返回默认统计数据
      return {
        totalUsers: 0,
        totalUsersGrowth: 0,
        activeUsers: 0,
        activeUsersGrowth: 0,
        vipUsers: 0,
        vipUsersGrowth: 0,
        newUsersToday: 0,
        newUsersTodayGrowth: 0,
      };
    }
  }

  /**
   * 删除用户
   */
  static async deleteUser(userId: string): Promise<boolean> {
    try {
      const response = await fetch(`${this.baseURL}/users/${userId}`, {
        method: "DELETE",
      });

      if (!response.ok) {
        throw new Error("删除用户失败");
      }

      return true;
    } catch (error) {
      console.error("删除用户失败:", error);
      return false;
    }
  }

  /**
   * 批量操作用户
   */
  static async batchUpdateUsers(userIds: string[], updates: Partial<User>): Promise<boolean> {
    try {
      const response = await fetch(`${this.baseURL}/users/batch`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          userIds,
          updates,
        }),
      });

      if (!response.ok) {
        throw new Error("批量更新用户失败");
      }

      return true;
    } catch (error) {
      console.error("批量更新用户失败:", error);
      return false;
    }
  }

  /**
   * 执行用户管理操作
   */
  static async executeUserAction(
    userId: string,
    action: UserManagementAction,
    operatorId: string,
    operatorName: string,
  ): Promise<boolean> {
    try {
      const response = await fetch(`${this.baseURL}/users/${userId}/actions`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          action,
          operatorId,
          operatorName,
        }),
      });

      if (!response.ok) {
        throw new Error("执行用户操作失败");
      }

      return true;
    } catch (error) {
      console.error("执行用户操作失败:", error);
      return false;
    }
  }

  /**
   * 创建新用户
   */
  static async createUser(userData: {
    email: string;
    nickname: string;
    password: string;
    role?: string;
    status?: string;
    vipStatus?: string;
    level?: number;
    balance?: number;
    avatar?: string;
  }): Promise<boolean> {
    try {
      const response = await fetch(`${this.baseURL}/users`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(userData),
      });

      if (!response.ok) {
        throw new Error("创建用户失败");
      }

      const result = await response.json();
      return result.success;
    } catch (error) {
      console.error("创建用户失败:", error);
      return false;
    }
  }

  /**
   * 导出用户数据
   */
  static async exportUsers(format: "csv" | "excel" = "csv"): Promise<Blob> {
    try {
      const response = await fetch(`${this.baseURL}/users/export?format=${format}`);
      if (!response.ok) {
        throw new Error("导出用户数据失败");
      }

      return await response.blob();
    } catch (error) {
      console.error("导出用户数据失败:", error);
      throw error;
    }
  }

  /**
   * 搜索用户
   */
  static async searchUsers(
    query: string,
    filters?: {
      status?: string;
      vipStatus?: string;
      role?: string;
    },
  ): Promise<User[]> {
    try {
      const params = new URLSearchParams({
        q: query,
        ...filters,
      });

      const response = await fetch(`${this.baseURL}/users/search?${params}`);
      if (!response.ok) {
        throw new Error("搜索用户失败");
      }

      const data = await response.json();
      return data.users || [];
    } catch (error) {
      console.error("搜索用户失败:", error);
      return [];
    }
  }
}
